/**
 * 注册。登录
 * express node的服务器框架
 * gravatar 全球头像
 * Passport 是一个扩展性很强的认证中间件，
 */
const express = require("express");
const jwt = require("jsonwebtoken");
const keys = require("../../config/keys");
const md5 = require("md5");
const passport = require("passport");
const querystring = require("querystring");
const request = require("request");
const { URL } = require("../../config/keys");
const router = express.Router();
const multiparty = require("multiparty");
//导入数据库的视图
const User = require("../../models/User");

var verification = {};
router.post("/code", (req, res) => {
  User.findOne({
    phone: req.body.phone,
  }).then((data) => {
    if (data) {
      res.json({
        success: false,
        msg: "手机号码已被注册",
      });
    } else {
      let code = ("000000" + Math.floor(Math.random() * 999999)).slice(-6);
      verification[req.body.phone] = code;
      if (process.env.API_ENV === "prod") {
      } else {
        res.json({
          success: false,
          msg: code,
        });
      }
    }
  });
});

router.post("/register", (req, res) => {
  User.find({
    phone: req.body.phone,
  }).then((user) => {
    if (user.length != 0) {
      return res.json({
        success: false,
        msg: "手机号已被注册",
      });
    } else {
      if (req.body.code != verification[req.body.phone]) {
        return res.json({
          success: false,
          msg: "验证码错误",
        });
      }
      // console.log('fg')
      const newUser = new User({
        phone: req.body.phone,
        password: md5(req.body.password),
        name: req.body.name,
      });
      newUser
        .save()
        .then((user) =>
          res.json({
            success: true,
            msg: "注册成功",
          })
        )
        .catch((err) => console.log(err));
    }
  });
});

router.post("/login", (req, res) => {
  console.log(req.body.email);
  //判断数据库中是否有email
  User.findOne({
    $or: [
      {
        username: req.body.username,
      },
      {
        phone: req.body.phone,
      },
    ],
  }).then((user) => {
    if (!user)
      res.json({
        success: false,
        msg: "账号不存在",
      });
    else {
      if (user.password == md5(req.body.password)) {
        const rule = {
          id: user.id,
          name: user.name,
          grade: user.grade,
          avatar: URL + user.avatar,
        };
        //  jwt.sign('规则','加密名字','过期时间','箭头函数') session的规则
        jwt.sign(
          rule,
          keys.secretOrKey,
          {
            expiresIn: 3600,
          },
          (err, token) => {
            if (err) throw err;
            res.json({
              success: true,
              token: "Bearer " + token,
              result: {
                id: user.id,
                phone: user.phone,
                username: user.username,
                name: user.name,
                grade: user.grade,
                avatar: URL + user.avatar,
              },
            });
          }
        );
      } else {
        return res.json({
          success: false,
          msg: "密码错误",
        });
      }
    }
  });
});

router.post("/update", async (req, res) => {
  var list = {};
  if (req.body.password) {
    await User.findOne({
      _id: req.body._id,
    })
      .then((user) => {
        if (user.password == md5(req.body.password)) {
          console.log("222", user.password, md5(req.body.password));
          list = {
            password: md5(req.body.newpassword),
          };
        } else {
          return res.json({
            success: false,
            msg: "密码不正确",
          });
        }
      })
      .catch((e) => {});
  } else if (req.body.name) {
    list = {
      name: req.body.name,
      _id: req.body._id,
    };
  } else if (req.body.phone) {
    if (req.body.code != verification[req.body.phone]) {
      return res.json({
        success: false,
        msg: "验证码错误",
      });
    } else {
      await User.find({
        phone: req.body.phone,
      }).then((user) => {
        if (user.length != 0) {
          return res.json({
            success: false,
            msg: "手机号已被注册",
          });
        } else {
          // console.log('fg')
          list = {
            phone: req.body.phone,
            _id: req.body._id,
          };
        }
      });
    }
  }
  await User.update(
    {
      _id: req.body._id,
    },
    list
  )
    .then((user) => {
      res.json({
        success: true,
        msg: "数据更新成功",
      });
    })
    .catch((err) => {
      res.json({
        success: false,
        msg: "数据更新失败",
      });
    });
});

router.post("/updateList", (req, res) => {
  var list = {};
  console.log(req.body);
  if (req.body.password) {
    list = {
      name: req.body.name,
      email: req.body.email,
      grade: req.body.grade,
      _id: req.body._id,
      phone: req.body.phone,
      password: md5(req.body.password),
    };
  } else {
    list = {
      name: req.body.name,
      phone: req.body.phone,
      email: req.body.email,
      grade: req.body.grade,
      _id: req.body._id,
    };
  }

  User.update({ _id: req.body._id }, list)
    .then((user) => {
      res.json({ success: true, msg: "数据更新成功" });
    })
    .catch((err) => {
      res.json({ success: false, msg: "数据更新失败" });
    });
});

router.get(
  "/alls",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    if (req.user.grade >= 999) {
      User.find({
        username: {
          $ne: "admin",
        },
      }).then((users) => {
        res.json({ success: true, result: users });
      });
    } else {
      res.json({ success: false, msg: "权限不够" });
    }
  }
);
router.get(
  "/administrator",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    if (req.user.username === "admin") {
      User.find({
        username: {
          $ne: "admin",
        },
        grade: {
          $gte: 999,
        },
      }).then((users) => {
        res.json({ success: true, result: users });
      });
    } else {
      res.json({ success: false, msg: "权限不够" });
    }
  }
);
router.post(
  "/updateGrade",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    if (req.user.username === "admin") {
      let grade = req.body.grade === true ? 999 : 0;
      User.update(
        { _id: req.body._id },
        {
          grade: grade,
        }
      ).then((users) => {
        res.json({ success: true, msg: "更新成功" });
      });
    } else {
      res.json({ success: false, msg: "权限不够" });
    }
  }
);

/**
 * @name 修改用户的头像
 * @author Robert
 * @method delete
 * @url api/users/delete
 * @param
 *     id   被修改用户的id
 * @returns
 *    success: true, msg: '删除成功'
 */

// 上传图片
router.post(
  "/updateUser",
  passport.authenticate("jwt", { session: false }),
  (req, res) => {
    console.log(req);
    var form = new multiparty.Form();
    form.uploadDir = "static/img/user";
    form.parse(req, function (err, fields, files) {
      var path = files.url[0].path.split("\\");
      path = path.join("/");
      var result = URL + path;
      User.update(
        {
          _id: req.user._id,
        },
        {
          avatar: path,
        }
      )
        .then((user) => {
          res.json({ success: true, url: result });
        })
        .catch((err) => {
          res.json({
            success: false,
            msg: "数据更新失败",
          });
        });
    });
  }
);

router.get("/delete/:id", (req, res) => {
  User.remove({ _id: req.params.id })
    .then((user) => {
      res.json({ success: true, msg: "删除成功" });
    })
    .catch((err) => {
      res.json({ success: false, msg: "删除失败" });
    });
});

module.exports = router;
